"""Targets的增删改查 """
import io

from awvs.base import Base
from lib.cache import file_cache
import pandas as pd
from utils.log import logger

class Targets(Base):
    @property
    def __target_fields(self):
        return [
            'address',
            'description',
            'criticality',
            'last_scan_date',
            'last_scan_id',
            'target_id',
            'severity_counts.high',
        ]

    @property
    def targets(self):
        api = f'{self.url}/targets'
        r = self.session.get(api)
        result = self.scroll_pages(r, api, 'targets')
        targets = Base.parse_fields(result, self.__target_fields)
        return targets

    @file_cache(Base.cache_base)
    def add_target(self, address: str, description='', type='default', criticality='10') -> dict:
        api = f'{self.url}/targets'
        data = {
            'address': address,
            'description': description,
            'type': type,
            'criticality': criticality
        }
        r = self.session.post(api, json=data)

        if r.status_code == 201:
            print(f'{address} 添加成功')
            return r.json()
        else:
            return {}

    def get_target_id(self, addresses:list) -> dict:
        targets = self.targets
        results = {}
        for address in addresses:
            target_id = targets.query(lambda x: x.address == address)['target_id'].values[0]
            results[target_id] = address
        return results
            
        
    @file_cache()
    def add_targets(self, addresses: list, description='', type='default', criticality=10, groups=[]) -> list:
        api = f'{self.url}/targets/add'
        addresses = list(set(addresses))
        templates = {
            'targets': [],
            'groups': groups
        }
        # TODO: 将已添加的列表复制对应group中
        for address in addresses:
            per = dict(address=address, description=description, type=type, criticality=criticality)
            templates['targets'].append(per)

        r = self.session.post(api, json=templates)
        if r.status_code == 200:
            logger.info(f'存活域名已添加到AWVS中')
            return r.json()['targets']
        return []

    def query(self, lambda_func):
        return self.targets[self.targets.apply(lambda_func, axis=1)]

    def remove_target(self, target_id: str) -> bool:
        api = f'{self.url}/targets/{target_id}'
        r = self.session.delete(api)
        if r.status_code == 200 or r.status_code == 204:
            return True
        return False

    def remove_targets(self, target_id_list: list) -> bool:
        """批量删除目标
        
        Args:
            target_id_list: 要删除目标的target_id组成的列表
        
        Returns:
            True or False
        """
        api = f'{self.url}/targets/delete'
        templates = {
            'target_id_list': target_id_list
        }
        r = self.session.post(
            api,
            json=templates
        )
        if r.status_code == 204:
            return True
        return False

    def configure_target(self, target_id):
        pass
    
    def export_to_dataframe(self):
        api = f'{self.url}/targets/cvs_export'
        r = self.session.get(api)
        df = pd.read_csv(io.StringIO(r.content.decode()))
        return df
